package com.neusoft.work.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.work.dao.CareProjectDao;
import com.neusoft.work.dao.CareRecordDao;
import com.neusoft.work.dao.CustomerCarePlanDao;
import com.neusoft.work.dao.UserDao;
import com.neusoft.work.dto.CareRecordDTO;
import com.neusoft.work.po.CareProject;
import com.neusoft.work.po.CareRecord;
import com.neusoft.work.po.CustomerCarePlan;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.po.User;
import com.neusoft.work.service.CareRecordService;

@Service
public class CareRecordServiceImpl implements CareRecordService {

    @Autowired
    private CareRecordDao careRecordDao;
    @Autowired
    private UserDao      userDao;        // 护理员和其它用户共用 User 实体
    @Autowired
    private CareProjectDao careProjectDao;
    @Autowired
    private CustomerCarePlanDao carePlanDao;   // 增加这一行

    @Override
    public PageResponseBean<List<CareRecordDTO>> queryByCustomerId(
            Integer customerId, Long cur, Long number, String start, String end) {

        // 1. 分页查询 CareRecord
        Page<CareRecord> page = new Page<>(cur, number);
        QueryWrapper<CareRecord> qw = new QueryWrapper<>();
        qw.eq("customerId", customerId)
          .eq("isDeleted", false);
        if (start != null && end != null) {
            qw.between("careTime", start, end);
        }
        Page<CareRecord> result = careRecordDao.selectPage(page, qw);

        // 2. 收集所有 护理员 userId 和 项目 projectId
        List<CareRecord> recs = result.getRecords();
        List<Integer> staffIds   = recs.stream()
                                        .map(CareRecord::getCareStaffId)
                                        .distinct()
                                        .collect(Collectors.toList());
        List<Integer> projectIds = recs.stream()
                                        .map(CareRecord::getCareProjectId)
                                        .distinct()
                                        .collect(Collectors.toList());

     // 3. 批量加载 User（护理员）和 CareProject
        Map<Integer, User> staffMap;
        if (!staffIds.isEmpty()) {
            staffMap = userDao.selectBatchIds(staffIds)
                              .stream()
                              .collect(Collectors.toMap(User::getId, Function.identity()));
        } else {
            staffMap = Collections.emptyMap();
        }

        Map<Integer, CareProject> projectMap;
        if (!projectIds.isEmpty()) {
            projectMap = careProjectDao.selectBatchIds(projectIds)
                                       .stream()
                                       .collect(Collectors.toMap(CareProject::getId, Function.identity()));
        } else {
            projectMap = Collections.emptyMap();
        }

        // 4. 组装 DTO
        List<CareRecordDTO> dtoList = new ArrayList<>();
        for (CareRecord cr : recs) {
            CareRecordDTO dto = new CareRecordDTO();
            dto.setId(cr.getId());
            dto.setCareTime(cr.getCareTime());
            dto.setQuantity(cr.getQuantity());
            dto.setContent(cr.getContent());

            // 从 User 表获取 护理员 信息
            User staff = staffMap.get(cr.getCareStaffId());
            if (staff != null) {
                dto.setStaffName(staff.getRealName());
                dto.setStaffPhone(staff.getPhoneNumber());
                dto.setStaffEmail(staff.getEmail());
            }

            // 项目信息
            var project = projectMap.get(cr.getCareProjectId());
            if (project != null) {
                dto.setProjectName(project.getName());
                dto.setProjectPrice(project.getPrice());
            }

            dtoList.add(dto);
        }

        // 5. 返回分页结果
        PageResponseBean<List<CareRecordDTO>> resp = new PageResponseBean<>();
        resp.setData(dtoList);
        resp.setTotal(result.getTotal());
        return resp;
    }

    @Override
    @Transactional
    public ResponseBean<Integer> deleteCareRecord(Integer id) {
        CareRecord update = new CareRecord();
        update.setId(id);
        update.setIsDeleted(true);
        int rows = careRecordDao.updateById(update);
        return rows > 0
            ? new ResponseBean<>(id)
            : new ResponseBean<>(500, "隐藏失败");
    }

    @Override
    @Transactional
    public ResponseBean<Integer> addCareRecord(CareRecord careRecord) {
        // 1. 插入护理记录
        careRecord.setIsDeleted(false);
        int rows = careRecordDao.insert(careRecord);
        if (rows <= 0) {
            return new ResponseBean<>(500, "添加护理记录失败");
        }
        
        CareProject project = careProjectDao.selectById(careRecord.getCareProjectId());
        if (project == null) {
            return new ResponseBean<>(500, "项目不存在");
        }
        String code = project.getCode();
        
        // 2. 扣减余量
        //    假设 CustomerCarePlan 实体里有 id, customerId, careProjectId, quantity…
        QueryWrapper<CustomerCarePlan> qw = new QueryWrapper<>();
        qw.eq("customerId", careRecord.getCustomerId())
          .eq("careProjectCode", code);
        CustomerCarePlan plan = carePlanDao.selectOne(qw);
        if (plan == null) {
        	return new ResponseBean<>(500,"没有找到对应的护理计划");
        }
        int newQty = plan.getQuantity() - careRecord.getQuantity();
        if (newQty < 0) {
            return new ResponseBean<>(500,"护理次数超出余量");
        }
        plan.setQuantity(newQty);
        carePlanDao.updateById(plan);

        // 3. 返回
        return new ResponseBean<>(careRecord.getId());
    }
    
    @Override
    public List<CareRecord> listByCareStaffId(Integer careStaffId) {
        QueryWrapper<CareRecord> qw = new QueryWrapper<>();
        qw.eq("careStaffId", careStaffId)
          .eq("isDeleted", false)      // 过滤软删标志
          .orderByDesc("careTime");    // 可按时间倒序
        return careRecordDao.selectList(qw);
    }
}
